<template>
	<view class="pad20 bg-grey">
		<sb-back-icon></sb-back-icon>
		<sb-search @search='handleSearch' />
		<view v-if="historyList.length">
			<view class="bold mar30 u-flex j-s">
				<view> Search History </view>
				<u-icon name="trash" color="#ccc" size="28" @click="handleClear"></u-icon>
			</view>
			<view class="flex mar20">
				<view class=" mar10 padh15 pill" v-for="(item, index) in historyList" :key="index"
					@click="handleSearch(item)">
					{{ item }}
				</view>
			</view>
		</view>
		<sb-line></sb-line>
		<view>
			<view class="bold marh30 marv10"> Popular Search </view>
			<view class="flex mar20">
				<view v-for="(item, i) in hotKeyList" :key="i" class="pill mar10 padh15"
					@click="handleSearch(item.label)">
					{{ item.label }}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { KEY_SEARCH_HISTORY } from '@/config/constant.js'

	export default {
		data() {
			return {
				historyList: [],
				hotKeyList: [],
			};
		},
		methods: {
			async handleClear() {
				await this.$confirm("Confirm To Clear ?");
				this.$removeCache(KEY_SEARCH_HISTORY);
				this.historyList = [];
			},
			async getPupularSearch() {
				let { success, data } = await this.$get("/search-keywords/list", {
					pageIndex: 1,
					pageSize: 10,
					keywords: this.keywords,
				}, false);
				if (success) this.hotKeyList = data.rows;
			},
			async handleSearch(keywords) {
				keywords = keywords.trim()
				// 搜索关键字缓存
				if (keywords && !this.historyList.includes(keywords)) {
					this.historyList.unshift(keywords);
					this.$setCache(KEY_SEARCH_HISTORY, this.historyList);
				}
				this.$go2(this.$makeUrl(`/pages/main/goods/list`, {
					keywords
				}));
			},
			getHistory() {
				this.historyList = this.$getCache(KEY_SEARCH_HISTORY) || [];
			},
		},
		onLoad() {
			this.getPupularSearch();
			this.getHistory();
		},
	};
</script>

<style lang="scss" scoped>
	.pill {
		background-color: #eee;
		border-radius: 8rpx;
		color: #333;
		font-size: 24rpx;
		padding: 10rpx 20rpx;
	}
</style>
